<template>
    <div>
         <page-header @toLastPage="toLastPage">
        <template v-slot:title>
        发红包
      </template>
      <template v-slot:right>
        <div>
          ...
        </div>
      </template>
        </page-header>
        <div class="content">
           <div class="money-wrapper flex">
               <div class="left">单个金额</div>
              <input type="number" @keydown="handleInput" name="" id="" v-model="money" placeholder="0.00" oninput="if(value>200)value=200" class="money-input">
               <div class="right">元</div>
           </div>
            <van-field
            v-model="message"
            label=""
            right-icon="balance-o"
            
            placeholder="恭喜发财，大吉大利"
        />
        <div class="cover flex">
            <div class="cover-left">红包封面</div>
            <div class="cover-right">
                <span></span>
                <van-icon name="arrow" />
            </div>
        </div>
        <div class="money-show">
            <div class="show-top">
                ¥{{showMoney}}
            </div>
            <van-button color="#F85050" :disabled='disabled' @click="sendPacket">塞钱进红包</van-button>
        </div>
        </div>
        <div class="tip">
            未领取的红包，将于24小时后发起退款
        </div>
        <loading v-if="showLoading"></loading>
    </div>
</template>
<script>
import pageHeader from '../common/pageHeader';
import loading from '../common/loading';
import { friends,messages, user } from '../../../api/collections/index';
export default {
    components:{
        pageHeader,
        loading
    },
      meteor: {
    $subscribe: {
      'userInf': []
    },
      messageList(){
     return messages.find({$or:[{M_ToUserID:this.userId,M_FromUserID:this.friendId,M_IsGroup:false},{M_ToUserID:this.friendId,M_FromUserID:this.userId,M_IsGroup:false}]}).fetch()
      }
      },
    data() {
        return {
            money:'',
            message:'',
            userId:sessionStorage.getItem('user'),
            friendId:this.$route.params.id,
            showLoading:false,
            pay:0
        }
    },
    methods:{
        handleInput(e){
            e.target.value = (e.target.value.match(/^\d*(\.?\d{0,1})/g)[0]) || null
        },
        toLastPage(){
            this.$router.go(-1)
        },
        sendPacket(){
            const userInf = user.findOne({_id:this.userId})
            if(userInf){
                this.pay = userInf.pay
                if(userInf.pay<this.money){
                    return this.$toast.fail('零钱不足，请先充值')
                }
            }
            const mine = friends.findOne({F_UserID:this.userId,F_FriendID:this.friendId})
            const yours = friends.findOne({F_UserID:this.friendId,F_FriendID:this.userId})
            if(!yours){
                this.$toast.fail('发送失败，对方已将您删除好友')
            }
            else if(mine.F_isBlock){
                this.$toast.fail('对方已被您拉黑，请取消后再操作')
            }
            else if(yours.F_isBlock){
                this.$toast.fail('发送失败，对方已将您拉入黑名单')
            }
            else{
                this.showLoading = true
                let data = {
                money:this.money,
                message:this.message||'恭喜发财，大吉大利',
                cover:'',
                isOpen:false
            }
             var obj = {
                M_PostMessages:data,
                M_Status:false,
                M_Time:new Date().getTime(),
                M_MessagesType:'packet',
                M_FromUserID:this.userId,
                M_ToUserID:this.friendId,
                M_IsGroup:false
             }
                this.sendText(obj);
            }

        },
    sendText(e){
      let data = ''
      Meteor.call('message.create',e,(err,res)=>{
        if(err){
          this.$toast(err.error)
        }else{
            data = res
        }
      })
      setTimeout(()=>{
         this.createIndexMsg(this.userId,this.friendId,data)
        this.createIndexMsg(this.friendId,this.userId,data)
         Meteor.call('user.updatePay',{
             id:this.userId,
             pay:Number(this.pay)-Number(this.money)
         })
        this.showLoading = false
        this.$toast.success('红包已发送')
        this.$router.go(-1)
      },500)
    },
        // 建立首页消息表
    createIndexMsg(id1,id2,data){
        var msg = {
        I_UserId:id1,
        I_OtherId:id2,
        I_Type:'person',
        I_LastMsgId:data,
        I_isTop:false
      }
      let num = 0
      if(this.messageList){
        this.messageList.forEach((e) => {
        if(e.M_FromUserID == id2 && e.M_ToUserID == id1 && e.M_Status == false){
          num = num+1
        }
      })
      }
      msg.I_noReadCount = num
      Meteor.call('indexMsg.create',msg) 
    },
    },
    computed:{
        showMoney(){
            if(this.money==''){
                return '0.00'
            }else{
               return Number(this.money).toFixed(2)
            }
        },
        disabled(){
            if(this.money == 0 || this.money == ''){
                return true
            }else{
                return false
            }
        }
    }
}
</script>
<style scoped>
    .content{
        margin-top: 1.8rem;
        padding: .5rem;
    }
    .money-wrapper{
        background-color: #fff;
        border-radius: .2rem;
        padding: .5rem;
        font-size: .6rem;
    }
    .left{
        text-align-last: left;
        width: 3rem;
    }
    .money-input{
        border: none;
        background: none;
        outline: none;
        text-align: right;
        flex:1;
    }
    .right{
        width: 1rem;
        text-align: center;
    }
    .van-field{
        border-radius: .2rem;
        margin-top: .5rem;
    }
    .cover{
        padding: .5rem;
        font-size: .6rem;
        background-color: #fff;
        margin-top: .5rem;
    }
    .cover-left{
        text-align: left;
        width: 3rem;;
    }
    .cover-right{
        text-align: right;
        flex:1;
    }
    .money-show{
        width: 100%;
        text-align: center;
        margin-top: 1.5rem;
    }
    .show-top{
        font-size: 1.5rem;
        font-weight: 700;
    }
    .van-button{
        height: 1.5rem;
        margin-top: .5rem;
        width: 5.5rem;
    }
    .tip{
        font-size: .4rem;
        position: absolute;
        bottom: .8rem;
        width: 100%;
        text-align: center;
        color: #676767;
    }
</style>